package com.wsc.springbootmultidevdemo.msg.routing;

import com.rabbitmq.client.*;
import com.wsc.springbootmultidevdemo.msg.ConnectionUtil;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Worker2 {

    public static void main(String[] args) throws IOException, TimeoutException {
        Connection connection = ConnectionUtil.getConnection();
        Channel channel = connection.createChannel();

        String EXCHANGE_NAME = "routing";
        String QUEUE_NAME = channel.queueDeclare().getQueue();
        //声明交换机
        channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);

        //在消费者段绑定
        String[] routing = {"error","info","debug"};
        for (int i = 0; i <routing.length ; i++) {
            // 路由绑定队列
            channel.queueBind(QUEUE_NAME,EXCHANGE_NAME,routing[i]);
        }

        System.out.println("Consumer is waiting Receive Message");

        Consumer consumer = new DefaultConsumer(channel){
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                String message = new String(body,"UTF-8");
                System.out.println("[C] receive a message from queue :"+ message);
            }
        };
        channel.basicConsume(QUEUE_NAME,true,consumer);
    }

}
